/**
 * Created by KaiBo on 2016-12-2.
 */
(function($){
    $.fn.chartered=function(options){
        /*
         *属性
         * */
        var defaults = {
            // 在html标签中存放的属性名称；
            attr: "data-url",
            travelNum:0,
            citylNum:{},
            featurelNum:{},
            // 父元素默认为window
            container: window,
            //行程数据
            travel:[
                {
                    startCity:{
                        id:null,
                        name:null,
                        features:[]
                    },
                    endCity:{
                            id:null,
                            name:null,
                            features:[]
                        },
                    wayCity:[

                    ]
                }
            ],
            //城市数据
            cityData:[],
            //景点数据aj
            featureUrl:null,
            //景点信息列表
            featureInfo:[]
        };
        var _this = this;
        var avtiveCity = null;             //正在操作的城市数组
        var avtiveObject = null;             //正在操作的城市对象
        var $modal = $("#featureModal");  //景点弹窗
        // 不管有没有传入参数，先合并再说；
        var params = $.extend({}, defaults, options || {});

        /*
         *函数
         * */

        //初始化
        _this.Init = function(){
            var html = '<option value="0">请选择城市</option>';
            for(var i in params.cityData){
                html += '<option value="'+params.cityData[i].UNID+'">'+params.cityData[i].CNAME+'</option>';
            }
            $(".chartered-container1 select[data-type!='2']").append(html);


            if( params.initData && params.initData.length > 0){
                params.travel = [];
                for(var i in params.initData){
                    var day = _this.creatDay();
                    for(var j in params.initData[i]){
                        switch (j){
                            case "0":
                                day.startCity.id = params.initData[i][j].id;
                                day.startCity.name = params.initData[i][j].name;
                                day.startCity.features = params.initData[i][j].features;
                                break;
                            case "1":
                                day.endCity.id = params.initData[i][j].id;
                                day.endCity.name = params.initData[i][j].name;
                                day.endCity.features = params.initData[i][j].features;
                                break;
                            default:
                                var city = {
                                    id:null,
                                    name:null,
                                    features:[]
                                };
                                city.id = params.initData[i][j].id;
                                city.name = params.initData[i][j].name;
                                city.features = params.initData[i][j].features;
                                day.wayCity.push(city);
                        }

                    }
                    params.travel.push(day);
                }
            }
            _this.rebuiltDay();
            _this.createRoute();
            _this.checkNum();
        };
        //构造行程树
        _this.createRoute = function () {
            var html = '';
            var json = [];
            for(var i in params.travel){
                var cities = [];
                var starCity = params.travel[i].startCity;
                if(starCity.id){
                    cities.push(starCity);
                }
                var wayCity = params.travel[i].wayCity;
                for(var j in wayCity){
                    cities.push(wayCity[j]);
                }
                if(cities.length > 0){
                    json.push(cities);
                }
                var endCity = params.travel[i].endCity;
                if(endCity.id){
                    cities.push(endCity);
                }
            }
            for(var i in json){
                var day = parseInt(i) + 1;
                html += '<div>';
                html += '      <h4>';
                html += '           第'+day+'日';
                html += '       </h4>';
                html += '       <ul>';
                for(var j in json[i]){
                    if(json[i][j].name){
                        html += '           <li>';
                        html += '               <span class="city-name">'+json[i][j].name+'</span>';
                        html += '               <div>';
                        for(var k in json[i][j].features){
                            html += '                   <span class="label ">'+json[i][j].features[k].name+'</span>';
                        }
                        html += '               </div>';
                        html += '           </li>';
                    }
                }
                html += '       </ul>';
                html += '    </div>';
            }
            if(params.route){
                $("input[name='ASSESS']").val(JSON.stringify(json).replace(/'/g,"\\'"));
                $(params.route).html(html);
            }
            if(params.map){
                $("input[name='"+params.map+"']").val(JSON.stringify(json).replace(/'/g,"\\'"));
            }

        };
        //显示景点编辑页
        _this.charteredShow = function (){
            $(".chartered-container1").hide();
            $(".chartered-bottom").hide();
            $(".navbar-top").hide();
            $(".chartered-container2").show();
        };
        //隐藏景点编辑页
        _this.charteredHide = function(){
            $(".chartered-container2").hide();
            $(".chartered-bottom").show();
            $(".navbar-top").show();
            $(".chartered-container1").show();
        };
        /**
         * 创建行程对象
         */
        _this.creatDay = function(){
            return {
                startCity:{
                    id:null,
                    name:null,
                    features:[]
                },
                endCity:{
                    id:null,
                    name:null,
                    features:[]
                },
                wayCity:[]
            };
        };
        /**
         *构建景点
         */
        _this.creatFeature = function(id,name,imgUrl){
            var html = '<div class="row feature-item" data-id="'+id+'" data-name="'+name+'">';
            html += '       <div class="col-xs-2">';
            html += '           <div class="img-item" style="background-image: url('+imgUrl+')"></div>';
            html += '       </div>';
            html += '       <div class="col-xs-8 feature-item-name ellipsis">'+name+'</div>';
            html += '       <div class="col-xs-2 feature-item-selected">';
            html += '           <span class="glyphicon glyphicon-ok-circle"></span>';
            html += '       </div>';
            html += '  </div>';
           return html;
        };
        /**
         * 构建途径城市
         */
        _this.creatWayCity = function(value,cityData){
            var index = $("#wayCity").children(".row").length +1;

            var html = '<div class="row">';
            html+='         <div class="col-xs-12 chartered-city" >';
            html+='             <div>';
            html+='                 <span class="glyphicon text-muted remove-wayCity glyphicon-minus-sign "></span>';
            html+='                 <label class="text-muted" for="">途径城市'+index+'</label>';
            html+='             </div>';
            html+='             <select class="form-control"  data-type="2">';
            html+='                 <option value="0" >请选择途径城市</option>';
            for(var i in cityData){
                if(value == cityData[i].UNID){
                    html+='<option selected="selected" value="'+cityData[i].UNID+'" >'+cityData[i].CNAME+'</option>';
                }else{
                    html+='<option value="'+cityData[i].UNID+'" >'+cityData[i].CNAME+'</option>';
                }
            }
            html+='              </select>';
            html+='           </div>';
            html+='           <div class="col-xs-12">';
            html+='               <ul class="features">';
            html+='               </ul>';
            html+='               <div class="add-feature">';
            html+='                   <span class="glyphicon glyphicon-plus-sign"></span>';
            html+='                   <span>编辑观光景点</span>';
            html+='               </div>';
            html+='           </div>';
            html+='     </div>';
            return html;
        };
        /*
        * 通过下标移除数据,从0开始
        * */
        _this.deleteData = function(index,data) {
            for (var i in data) {
                if (i == index) {
                    data.splice(i, 1);
                    return true;
                }
            }
            return false;
        };
        /**
         * 通过天数构建行程,day从1开始
         */
        _this.creatTravel = function(day){

            var $this = $(".day[data-index = '"+day+"']");
            $this.addClass("active").siblings(".day").removeClass("active");
            var index =  $this.attr("data-index") - 1;
            var travel = params.travel[index];
            //开始城市赋值
            var $startCity = $("select[data-type='0']");
            $startCity.children("option").each(function () {
                var $elem = $(this);
                var value = $elem.val();
                if (value == travel.startCity.id) {
                    $elem.prop("readonly", true);
                    $elem.prop("selected", true);
                } else {
                    $elem.attr("selected", false);
                }
            });
            if(day > 1){
                $startCity.prop("disabled",true);
            }else{
                $startCity.prop("disabled",false);
            }


            $startCity.parent(".chartered-city").next().children(".features").empty();
            for(var i in travel.startCity.features){
                var html = "<li>"+ travel.startCity.features[i].name +"</li>";
                $startCity.parent(".chartered-city").next().children(".features").append(html)
            }
            //结束城市赋值
            var $endCity = $("select[data-type='1']");
            $endCity.children("option").each(function(){
                var $elem = $(this);
                var value = $elem.val();
                if(value == travel.endCity.id){
                    $elem.prop("selected", true);
                }else{
                    $elem.attr("selected", false);
                }
            });

            $endCity.parent(".chartered-city").next().children(".features").empty();
            for(var i in travel.endCity.features){
                var html = "<li>"+ travel.endCity.features[i].name +"</li>";
                $endCity.parent(".chartered-city").next().children(".features").append(html)
            }
            //途径城市赋值
            var $wayCity = $("#wayCity");
            $wayCity.empty();
            for(var i in travel.wayCity){
                var k = parseInt(i)+ 1;
                $wayCity.append(_this.creatWayCity(travel.wayCity[i].id,params.cityData));
                $wayCity.children(".row:nth-child("+k+")").find(".features").empty();
                for(var j in travel.wayCity[i].features){
                    var html = "<li>"+travel.wayCity[i].features[j].name+"</li>";
                    $wayCity.children(".row:nth-child("+k+")").find(".features").append(html);
                }
            }

            //检测select
            $(".chartered-container1 select").each(function(){
                var $elem = $(this);
                if($elem.val() == '0'){
                    $elem.parent().removeClass('has-success').addClass("has-error");
                }else{
                    $elem.parent().removeClass('has-error').addClass('has-success');
                }
            });
        };
        /**
         * 构造天数列表
         */
        _this.rebuiltDay = function(){
            var $addDay = $(".add-day");
            $addDay.siblings(".day").remove();
            var html = "";
            for(var i in params.travel){
                var index = parseInt(i) +1;
                if(i == 0){
                    html = '<div class="day active" data-index="'+index+'">第'+index+'日</div>';
                }else{
                    html = '<div class="day" data-index="'+index+'">第'+index+'日</div>';
                }
                $addDay.before(html);
            }
            _this.creatTravel(1);
        };
        /**
         * 计算数组长度
         */
        _this.getLength = function(arry){
            var len = 0;
            for(var i in arry){
                len++;
            }
            return len;
        };
        /**
         * 通过下标判断城市是否存在数组中
         */
        _this.checkCitylNum = function(index){
            if(index == null || index == "0" || index == 0) return ;
            if(index in params.citylNum) {          //判断是否存在
                params.citylNum[index]++;
            }else{
                params.citylNum[index] = 1;
            }
        };
        /**
         * 通过下标判断景点是否存在数组中
         */
        _this.checkFeaturelNum = function(index){
            if(index == null || index == "0" || index == 0) return ;
            if(index in params.featurelNum) {       //判断是否存在
                params.featurelNum[index]++;
            }else{
                params.featurelNum[index] = 1;
            }
        };
        /**
         * 检测城市数与景点数，行程数
         */
        _this.checkNum = function(){
            params.travelNum = params.travel.length;
            params.citylNum = {};
            params.featurelNum = {};

            for(var i in params.travel){
                var index = params.travel[i].startCity.id;
                _this.checkCitylNum(index);
                for(var j in params.travel[i].startCity.features){
                    index = params.travel[i].startCity.features[j].id;
                    _this.checkFeaturelNum(index);
                };


                index = params.travel[i].endCity.id;
                _this.checkCitylNum(index);
                for(var j in params.travel[i].endCity.features){
                    index = params.travel[i].endCity.features[j].id;
                    _this.checkFeaturelNum(index);
                }


                for(var j in params.travel[i].wayCity){
                    index = params.travel[i].wayCity[j].id;
                    _this.checkCitylNum(index);
                    for(var k in params.travel[i].wayCity.features){
                        index = params.travel[i].wayCity.features[k].id;
                        _this.checkFeaturelNum(index);
                    }
                }

            }

            $("#travelNum").html(params.travelNum);
            $("#citylNum").html(_this.getLength(params.citylNum));
            $("#featurelNum").html(_this.getLength(params.featurelNum));

        };
        /**
         * 检测景点信息是否存在
         * 存在返回false
         */
        _this.checkFeatureInfo = function(unid){
            for(var i in params.featureInfo){
                if(unid == params.featureInfo[i].UNID){
                    return false;
                }
            }
            return true;
        };

        /**
         * 检查下拉菜单是否为空
         * false--有error
         */
        _this.checkSelect = function(){
            var flag = false;
            for(var i in params.travel){
                var index = parseInt(i)+1;
                if( !params.travel[i].startCity.id || params.travel[i].startCity.id =='0'){
                    _this.creatTravel(index);
                    return ;
                }
                if( !params.travel[i].endCity.id || params.travel[i].endCity.id == '0'){
                    _this.creatTravel(index);
                    return ;
                }
            }
            $(".chartered-container1 select").each(function(){
                var $elem = $(this);
                if($elem.val() == '0'){
                    $elem.parent().addClass("has-error");
                    flag = true;
                }
            });
            if(flag){
                return false;
            }else{
                return true;
            }
        };
        /**
         * 获取旅程json
         * @returns {void|*|string|XML}
         */
        _this.getJsonData = function () {
            var json = [];
            for(var i in params.travel){
                var cities = [];
                var starCity = params.travel[i].startCity;
                if(starCity.id){
                    cities.push(starCity);
                }
                var endCity = params.travel[i].endCity;
                if(endCity.id){
                    cities.push(endCity);
                }
                var wayCity = params.travel[i].wayCity;
                for(var j in wayCity){
                    cities.push(wayCity[j]);
                }
                if(cities.length > 0){
                    json.push(cities);
                }
            }
           return JSON.stringify(json).replace(/'/g,"\\'");
        };


        /*
        * 事件
        * */

        //天数点击事件
        $(document).on("click",".day",function(){
            var $this = $(this);
            var index =  $this.attr("data-index");
            _this.creatTravel(index);
            $this.addClass("active").siblings(".day").removeClass("active");
            _this.createRoute();
        });
        //增加天数事件
        $(".add-day").click(function(){

            if( !_this.checkSelect() ){
                return false;
            }

            var $this = $(this);
            var days = $(".day").length + 1;
            var html = '<div class="day" data-index="'+days+'">第'+days+'日</div>';
            var day = _this.creatDay();
            var index = parseInt(days) - 2;
            day.startCity.id = params.travel[index].endCity.id;
            day.startCity.name = params.travel[index].endCity.name;
            params.travel.push(day);
            $this.before(html);
            _this.creatTravel(days);
            var $day = $(".day[data-index = '"+days+"']");
            $day.addClass("active").siblings(".day").removeClass("active");
            _this.checkNum();
        });
        //下拉菜单点击事件
        $(document).on("change",".chartered-container1 select",function(){
            var $this = $(this);
            var cityType = $this.attr("data-type");
            var day = $(".day.active").attr("data-index") - 1;

            var cityId = $this.val();
            var cityName = $this.find("option:selected").text();

            switch (cityType){
                case "0":
                    params.travel[day].startCity.id=cityId;
                    params.travel[day].startCity.name=cityName;
                    params.travel[day].startCity.features=[];
                    break;
                case "1":
                    params.travel[day].endCity.id=cityId;
                    params.travel[day].endCity.name=cityName;
                    params.travel[day].endCity.features=[];

                    var nextIndex = parseInt(day) + 1;
                    if(nextIndex < params.travel.length ){
                        params.travel[nextIndex].startCity.id = params.travel[day].endCity.id;
                        params.travel[nextIndex].startCity.name = params.travel[day].endCity.name;
                        params.travel[nextIndex].startCity.features=[];
                    }
                    break;
                case "2":
                    var index = $this.parent(".chartered-city").parent().index();
                    params.travel[day].wayCity[index].id = cityId;
                    params.travel[day].wayCity[index].name = cityName;
                    params.travel[day].wayCity[index].features=[];


                    break;
                default:
                    alert("网络繁忙，请稍后再试。");
            }
            if( $this.parent(".chartered-city").hasClass("has-error") ){
                $this.parent(".chartered-city").removeClass("has-error");
            }
            $this.parent(".chartered-city").parent(".row").find(".features").empty();
            _this.checkNum();
            _this.createRoute();

        });
        //编辑观光景点
        $(document).on("click",".add-feature",function(){
            var $this = $(this);
            var $select = $this.parents(".col-xs-12").siblings(".chartered-city").find("select");
            var cityId = $select.val();
            avtiveObject = $this.siblings(".features");
            var cityName = $select.find("option:selected").text();
            var cityType = $select.attr("data-type");
            $(".active-city").html(cityName);
            var day = $(".day.active").attr("data-index") - 1;

            $('#feature-list').empty();
            $.post(params.featureUrl,{ID:cityId},function (data){
                var jsonData = eval("("+data+")");
                for(var i in jsonData){
                    if(_this.checkFeatureInfo(jsonData[i].UNID)){
                        params.featureInfo.push(jsonData[i]);
                    }
                    $('#feature-list').append(_this.creatFeature(jsonData[i].UNID,jsonData[i].NAME,jsonData[i].THUMB));
                }
            });
            if(cityId != 0){
                switch (cityType){
                    case "0":
                        avtiveCity = params.travel[day].startCity;
                        _this.charteredShow();
                        break;
                    case "1":
                        avtiveCity = params.travel[day].endCity;
                        _this.charteredShow();
                        break;
                    case "2":
                        var index = $select.parent(".chartered-city").parent().index();
                        avtiveCity = params.travel[day].wayCity[index];
                        _this.charteredShow();
                        break;
                    default:
                        alert("网络繁忙！，请稍后再试。");
                }
            }else{
                $select.parent().addClass("has-error")
            }
        });
        //完成
        $(".btn-complete").click(function(){
            avtiveCity.features = [];
            avtiveObject.empty();
            $(".feature-item").each(function(){
                var $this = $(this);
                var featureId = $this.attr("data-id");
                var featureName = $this.attr("data-name");
                var select = $this.children(".feature-item-selected");
                if(select.hasClass("active")){
                    avtiveCity.features.push({id:featureId,name:featureName});
                    var html = "<li>"+featureName+"</li>";
                    avtiveObject.append(html)
                }
            });
            _this.charteredHide();
            _this.checkNum();
            _this.createRoute();

        });
        //景点选择事件
        $(document).on("click",".feature-item-selected",function(){
            var $this = $(this);
            if($this.hasClass("active")){
                $this.removeClass("active");
            }else{
                $this.addClass("active");
            }
        });
        //景点点击事件
        $(document).on("click",".feature-item-name",function(){
            var $this = $(this);
            var featureId = $this.parent(".feature-item").attr("data-id");
            for(var i in params.featureInfo){
                if(featureId == params.featureInfo[i].UNID){
                    $("#featureName").html(params.featureInfo[i].NAME);
                    $("#featureDetail").html(params.featureInfo[i].DETAIL);
                    $("#featureImg").prop("src",params.featureInfo[i].PATH);
                    break;
                }
            }
            $modal.modal();
        });
        //添加城市
        $(".btn-addCity").click(function(){
            var day = $(".day.active").attr("data-index") - 1;
            params.travel[day].wayCity.push({
                id:null,
                name:null,
                features:[]
            });
            $("#wayCity").append(_this.creatWayCity(null,params.cityData));
            _this.checkNum();
        });
        //移除城市
        $(document).on('click','.remove-wayCity',function(){
            var $this = $(this);
            var $row = $this.parents(".chartered-city").parent();
            var index = $row.index();
            var $activeDay = $(".day.active");
            var day = $activeDay.attr("data-index") - 1;
            if(_this.deleteData(index,params.travel[day].wayCity)){
                $row.remove();
                index = day + 1;
                _this.creatTravel(index);
            }
            _this.createRoute();

        });
        //移除行程
        $(".btn-removeDay").click(function(){
            var $activeDay = $(".day.active");
            var day = $activeDay.attr("data-index") - 1;
            if(day > 0){
                if(_this.deleteData(day,params.travel)){
                    $activeDay.remove();
                    $(".day[data-index = '"+day+"']").addClass("active");
                    _this.creatTravel(day);
                    _this.rebuiltDay();
                }
            }
            _this.checkNum();
            _this.createRoute();
        });
        //估价
        $(".btn-assess").click(function(){

            if( !_this.checkSelect() ){
                return false;
            }

            var json = [];
            for(var i in params.travel){
                var cities = [];
                var starCity = params.travel[i].startCity;
                if(starCity.id){
                    cities.push(starCity);
                }
                var wayCity = params.travel[i].wayCity;
                for(var j in wayCity){
                    cities.push(wayCity[j]);
                }
                if(cities.length > 0){
                    json.push(cities);
                }
                var endCity = params.travel[i].endCity;
                if(endCity.id){
                    cities.push(endCity);
                }
            }
            $("input[name='ASSESS']").val(JSON.stringify(json).replace(/'/g,"\\'"));
        });


        /**
         * 执行
         */
        _this.Init();
    }
}(jQuery));